#include "stdafx.h"
#include "svm.h"
#include "common.h"


#include <fstream>
#include <sstream>

using std::ifstream;
using std::istringstream;



inline pair<int, double> node_str_to_pair(const string node_str) {
	int i = node_str.find(":");
	return pair<int, double>(stoi(node_str.substr(0, i)), stod(node_str.substr(i + 1, node_str.size())));
}

void read_data_from_libsvm(vector<int> &label, 
					vector<vector<pair<int, double>>>& features, const string& file_name) {
	ifstream input(file_name);
	string line;
	size_t num_samples = 0;
	while (getline(input, line)) {
		//cout << line << endl;
		istringstream line_reader(line);
		// read y
		int y;
		line_reader >> y;
		label.push_back(y);

		// read x
		vector<pair<int, double>> temp;
		string node_str;
		while (line_reader >> node_str) {
			temp.push_back(node_str_to_pair(node_str));
		}
		features.push_back(temp);

		num_samples++;
	}
	input.close();
}